package com.ruoyi.bpm.service.definition.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.bpm.controller.admin.definition.vo.listener.BpmProcessListenerPageReqVO;
import com.ruoyi.bpm.controller.admin.definition.vo.listener.BpmProcessListenerSaveReqVO;
import com.ruoyi.bpm.domain.definition.BpmProcessListener;
import com.ruoyi.bpm.enums.definition.BpmProcessListenerType;
import com.ruoyi.bpm.enums.definition.BpmProcessListenerValueType;
import com.ruoyi.bpm.mapper.definition.BpmProcessListenerMapper;
import com.ruoyi.bpm.service.definition.BpmProcessListenerService;
import com.ruoyi.bpm.utils.BeanUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.common.orm.core.service.impl.BaseServiceImpl;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.delegate.TaskListener;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static com.ruoyi.bpm.domain.definition.table.BpmProcessListenerTableDef.BPM_PROCESS_LISTENER;
import static com.ruoyi.bpm.enums.ErrorCodeConstants.*;
import static com.ruoyi.common.core.utils.ServiceExceptionUtil.exception;

/**
 * BPM 流程监听器 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BpmProcessListenerServiceImpl extends BaseServiceImpl<BpmProcessListenerMapper, BpmProcessListener> implements BpmProcessListenerService {

    @Override
    public QueryWrapper query() {
        return super.query().from(BPM_PROCESS_LISTENER);
    }

    @Override
    public Long createProcessListener(BpmProcessListenerSaveReqVO createReqVO) {
        // 校验
        validateCreateProcessListenerValue(createReqVO);
        // 插入
        BpmProcessListener processListener = BeanUtils.toBean(createReqVO, BpmProcessListener.class);
        mapper.insert(processListener);
        return processListener.getId();
    }

    @Override
    public void updateProcessListener(BpmProcessListenerSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessListenerExists(updateReqVO.getId());
        validateCreateProcessListenerValue(updateReqVO);
        // 更新
        BpmProcessListener updateObj = BeanUtils.toBean(updateReqVO, BpmProcessListener.class);
        super.updateById(updateObj);
    }

    private void validateCreateProcessListenerValue(BpmProcessListenerSaveReqVO createReqVO) {
        // class 类型
        if (createReqVO.getValueType().equals(BpmProcessListenerValueType.CLASS.getType())) {
            try {
                Class<?> clazz = Class.forName(createReqVO.getValue());
                if (createReqVO.getType().equals(BpmProcessListenerType.EXECUTION.getType())
                    && !JavaDelegate.class.isAssignableFrom(clazz)) {
                    throw exception(PROCESS_LISTENER_CLASS_IMPLEMENTS_ERROR, createReqVO.getValue(),
                        JavaDelegate.class.getName());
                } else if (createReqVO.getType().equals(BpmProcessListenerType.TASK.getType())
                    && !TaskListener.class.isAssignableFrom(clazz)) {
                    throw exception(PROCESS_LISTENER_CLASS_IMPLEMENTS_ERROR, createReqVO.getValue(),
                        TaskListener.class.getName());
                }
            } catch (ClassNotFoundException e) {
                throw exception(PROCESS_LISTENER_CLASS_NOT_FOUND, createReqVO.getValue());
            }
            return;
        }
        // 表达式
        if (!StrUtil.startWith(createReqVO.getValue(), "${") || !StrUtil.endWith(createReqVO.getValue(), "}")) {
            throw exception(PROCESS_LISTENER_EXPRESSION_INVALID, createReqVO.getValue());
        }
    }

    @Override
    public void deleteProcessListener(Long id) {
        // 校验存在
        validateProcessListenerExists(id);
        // 删除
        mapper.deleteById(id);
    }

    private void validateProcessListenerExists(Long id) {
        if (getProcessListener(id) == null) {
            throw exception(PROCESS_LISTENER_NOT_EXISTS);
        }
    }

    @Override
    public BpmProcessListener getProcessListener(Long id) {
        return super.getById(id);
    }

    @Override
    public TableDataInfo<BpmProcessListener> getProcessListenerPage(BpmProcessListenerPageReqVO pageReqVO) {
        QueryWrapper queryWrapper = query()
            .where(BPM_PROCESS_LISTENER.NAME.like(pageReqVO.getName(), StrUtil.isNotBlank(pageReqVO.getName())))
            .and(BPM_PROCESS_LISTENER.TYPE.eq(pageReqVO.getType(), StrUtil.isNotBlank(pageReqVO.getType())))
            .and(BPM_PROCESS_LISTENER.EVENT.eq(pageReqVO.getEvent(), StrUtil.isNotBlank(pageReqVO.getEvent())))
            .and(BPM_PROCESS_LISTENER.STATUS.eq(pageReqVO.getStatus(), pageReqVO.getStatus() != null))
            .orderBy(BPM_PROCESS_LISTENER.ID.desc());
        Page<BpmProcessListener> page = this.pageAs(PageQuery.build(), queryWrapper, BpmProcessListener.class);
        return TableDataInfo.build(page);
    }

}
